//
//  ImageDownloader.m
//  RBIOSBase
//
//  Created by ren on 27/09/2017.
//  Copyright © 2017 bryan. All rights reserved.
//

#import "ImageDownloader.h"
#import "ImageDownloaderOperation.h"
#import "CommonDefine.h"

@interface ImageDownloader ()<NSURLSessionDelegate,NSURLSessionDataDelegate>

@property (nonatomic, strong) NSMutableData *mutableData;
@property (strong, nonatomic) NSOperationQueue *downloadQueue;
@property (nonatomic, strong) dispatch_queue_t barrierQueue;

@end

@implementation ImageDownloader

- (instancetype)init
{
	if (self = [super init]) {
		_barrierQueue = dispatch_queue_create("com.bryan.WebImageDownloaderBarrierQueue", DISPATCH_QUEUE_CONCURRENT);
		self.mutableData = [NSMutableData data];
		_downloadQueue = [NSOperationQueue new];
		_downloadQueue.maxConcurrentOperationCount = 6;
		_downloadQueue.name = @"com.rbyyyemist.WebImageDownloader";
	}
	return self;
}

- (void)operationsList:(ImageDownloaderOperation *(^)(void))downloaderOperation
{
	
}


- (void)addOperationBlock
{
//	NSBlockOperation *blockOperation = [NSBlockOperation blockOperationWithBlock:^{
//		NSLog(@"currentQueue----->%@", [NSOperationQueue currentQueue]);
//	}];
//	[blockOperation start];
	
	NSInvocationOperation *invocationOperation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(testInvocationOperation:) object:@1];
	[invocationOperation start];
	
//	NSOperationQueue *queue = [NSOperationQueue currentQueue];
//	[queue addOperation:blockOperation];
//	[queue setMaxConcurrentOperationCount:5];
}

- (void)loadFromURLKey:(NSString *)urlKey
{
	NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlKey]];
	NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
	NSURLSession *urlSession = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
	dispatch_barrier_sync(self.barrierQueue, ^{
		ImageDownloaderOperation *downloaderOperation = [[ImageDownloaderOperation alloc] initWithSession:urlSession request:request];
		[self.downloadQueue addOperation:downloaderOperation];
	});
}

- (void)testInvocationOperation:(id)object
{
	NSLog(@"testInvocationOperation----->%@", object);
}

- (void)genURLSession
{
	NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://wx.qlogo.cn/mmhead/ver_1/bI1ezaHJ2eibyOdLHZ2YTNVIn1YeMBGYafN4seTxAhghwcCVzL5FWho2dlSIJRKpv53k4jVJA9vYdzPM7hOgC34avEOlq0PzsnaUAlvGqVlU/132"]];
	NSOperationQueue *operationQueue = [NSOperationQueue currentQueue];
	NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
	NSURLSession *urlSession = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:operationQueue];
	NSURLSessionDataTask *dataTask = [urlSession dataTaskWithRequest:request];
	[dataTask resume];
}

#pragma mark - NSURLSessionDelegate

// 1.接收到服务器的响应
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
	// 允许处理服务器的响应，才会继续接收服务器返回的数据
	completionHandler(NSURLSessionResponseAllow);
}

// 2.接收到服务器的数据（可能调用多次）
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
	// 处理每次接收的数据
	[self.mutableData appendData:data];
}

// 3.请求成功或者失败（如果失败，error有值）
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
	// 请求完成,成功或者失败的处理
	NSData *data = nil;
	if (self.mutableData) {
		data = [self.mutableData copy];
		self.mutableData = nil;
	}
	if (data) {
		
//		dispatch_main_async_safe(^{
//			if (self.reciverImage) {
//				NSString *keyUrlString = [task.response.URL absoluteString];
//				self.reciverImage(data, keyUrlString);
//			}
//		});
		if (self.reciverImage) {
			NSString *keyUrlString = [task.response.URL absoluteString];
			self.reciverImage(data, keyUrlString);
		}
		
	}
	[session finishTasksAndInvalidate];
}


@end
